package com.jingli.pile.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
public class HmacMd5Signature {
    private static final byte IPAD = 0x36;
    private static final byte OPAD = 0x5C;

    public static String hmacMd5(String data, String sigSecret) throws Exception {
        byte[] keyBytes = sigSecret.getBytes(StandardCharsets.UTF_8);
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);

        byte[] paddedKey = Arrays.copyOf(keyBytes, 64);
        byte[] xorIpad = new byte[64];
        byte[] xorOpad = new byte[64];

        for (int i = 0; i < 64; i++) {
            xorIpad[i] = (byte) (paddedKey[i] ^ IPAD);
            xorOpad[i] = (byte) (paddedKey[i] ^ OPAD);
        }

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(xorIpad);
        md.update(dataBytes);
        byte[] hashIpad = md.digest();

        byte[] finalData = new byte[64 + hashIpad.length];
        System.arraycopy(xorOpad, 0, finalData, 0, 64);
        System.arraycopy(hashIpad, 0, finalData, 64, hashIpad.length);

        md.reset();
        md.update(finalData);
        byte[] hmacMd5 = md.digest();

        StringBuilder result = new StringBuilder();
        for (byte b : hmacMd5) {
            result.append(String.format("%02x", b));
        }

        return result.toString().toUpperCase();
    }

    public static void main(String[] args) throws Exception {
        String sig = "CB1E267DEEF51152CB26246889DF045E";
        String signSecret = "8qkuf011kzwjsn9t";
        String platformID = "MA8N2HC57";
        String data = "O6CZGGG5c7ZY8W9m2mbUXCKW1oj4nlkj9AjhqJaIqGTtjftQujneF8L6aYkEPiEEHC503YVZ2ijlQhQSk21baA==";
        String timestamp = "20231124162727";
        String seq = "0001";
        String digest = hmacMd5(platformID + data + timestamp + seq,signSecret);
        System.out.println(digest);
        String signHex = HMacMd5Utils.signHex(signSecret, platformID, data, timestamp, seq);
        System.out.println(signHex);
    }
}
